<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
            <el-form-item label="表名称" prop="tableName">
                <el-input
                    v-model="queryParams.tableName"
                    placeholder="请输入表名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="表描述" prop="tableComment">
                <el-input
                    v-model="queryParams.tableComment"
                    placeholder="请输入表描述"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker
                    v-model="dateRange"
                    style="width: 240px"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                ></el-date-picker>
            </el-form-item>
            <el-form-item>
<!--                <el-select v-model="queryParams.genTemplateType" placeholder="语言框架">-->
<!--                    <el-option-->
<!--                        v-for="item in genTemplate.options"-->
<!--                        :key="item.value"-->
<!--                        :label="item.label"-->
<!--                        :value="item.value">-->
<!--                    </el-option>-->
<!--                </el-select>-->
<!--                <el-button type="primary" size="mini" @click="showGenTemplate">语言框架</el-button>-->
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-download"
                    size="mini"
                    @click="handleGenTable"
                >生成
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="info"
                    plain
                    icon="el-icon-upload"
                    size="mini"
                    @click="openImportTable"
                >导入
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleEditTable"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                >删除
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange" height="700">
            <el-table-column type="selection" align="center" width="55"></el-table-column>
            <el-table-column label="序号" type="index" width="50" align="center">
                <template slot-scope="scope">
                    <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="表名称"
                align="center"
                prop="tableName"
                :show-overflow-tooltip="true"
                width="500"
            />
            <el-table-column
                label="表描述"
                align="center"
                prop="tableComment"
                :show-overflow-tooltip="true"
                width="200"
            />
            <el-table-column
                label="实体"
                align="center"
                prop="className"
                :show-overflow-tooltip="true"
                width="200"
            />
            <el-table-column label="创建时间" align="center" prop="createTime" width="160"/>
            <el-table-column label="更新时间" align="center" prop="updateTime" width="160"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        type="text"
                        size="small"
                        icon="el-icon-view"
                        @click="handlePreview(scope.row)"
                    >预览
                    </el-button>
                    <el-button
                        type="text"
                        size="small"
                        icon="el-icon-edit"
                        @click="handleEditTable(scope.row)"
                    >编辑
                    </el-button>
                    <el-button
                        type="text"
                        size="small"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                    >删除
                    </el-button>
                    <el-button
                        type="text"
                        size="small"
                        icon="el-icon-refresh"
                        @click="handleSynchDb(scope.row)"
                    >同步
                    </el-button>
                    <el-button
                        type="text"
                        size="small"
                        icon="el-icon-download"
                        @click="handleGenTable(scope.row)"
                    >生成代码
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />
        <el-dialog title="编辑" :visible.sync="dialog.editTable.open" width="90%" append-to-body>
            <gen-edit v-if="dialog.editTable.open" :p="dialog.editTable.params" @callParentMethod="handleEditClose"/>
        </el-dialog>



        <!-- 预览界面 -->
        <el-dialog :title="preview.title" :visible.sync="preview.open" width="90%" top="5vh" append-to-body
                   >
            <el-tabs v-model="preview.activeName">
                <el-tab-pane
                    v-for="(value, key) in preview.data"
                    :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
                    :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
                    :key="key"
                >
                    <el-link :underline="false" icon="el-icon-document-copy" v-clipboard:copy="value"
                             v-clipboard:success="clipboardSuccess" style="float:right">复制
                    </el-link>
                    <pre><code class="hljs" v-html="highlightedCode(value, key)"></code></pre>
                </el-tab-pane>
            </el-tabs>
        </el-dialog>
        <import-table ref="import" @ok="handleQuery"/>
        <!-- 新增：模板类型选择弹窗 -->
        <el-dialog
            title="选择生成模板类型"
            :visible.sync="genTemplate.open"
            width="400px"
            append-to-body
        >
            <el-form label-width="120px" class="mt-20">
                <el-form-item label="模板类型">
                    <el-select
                        v-model="genTemplate.selectedType"
                        placeholder="请选择模板类型"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="item in genTemplate.options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="genTemplate.open = false">取消</el-button>
                <el-button type="primary" @click="confirmGenTemplate">确认生成</el-button>
            </div>
        </el-dialog>
    </div>

</template>

<script>
import {listTable, previewTable, delTable, genCode, synchDb} from "@/api/tool/gen";
import importTable from "./importTable";
import hljs from "highlight.js/lib/highlight";
import "highlight.js/styles/github-gist.css";
import GenEdit from "@/views/tool/gen/editTable";

hljs.registerLanguage("java", require("highlight.js/lib/languages/java"));
hljs.registerLanguage("xml", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("html", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("vue", require("highlight.js/lib/languages/xml"));
hljs.registerLanguage("javascript", require("highlight.js/lib/languages/javascript"));
hljs.registerLanguage("sql", require("highlight.js/lib/languages/sql"));
// 原有注册代码后新增 PHP 注册
hljs.registerLanguage("php", require("highlight.js/lib/languages/php"));
export default {
    name: "Gen",
    components: {GenEdit, importTable},
    data() {
        return {
            // 遮罩层
            loading: true,
            // 唯一标识符
            uniqueId: "",
            // 选中数组
            ids: [],
            // 选中表数组
            tableNames: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表数据
            tableList: [],
            // 日期范围
            dateRange: "",
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 50,
                tableName: undefined,
                tableComment: undefined,
                genTemplateType: "base",
            },
            // 预览参数
            preview: {
                open: false,
                title: "代码预览",
                data: {},
                activeName: "domain.java"
            },
            dialog:{
                editTable:{
                    open:false,
                    params:undefined
                }
            },        // 新增：模板类型选择配置
            genTemplate: {
                open: false, // 选择弹窗是否显示
                selectedType: "base", // 默认选中基础模板
                options: [ // 模板类型选项（与后端 GenConstants 对应）
                    { label: "基础 Java/Vue 模板", value: "base" },
                    { label: "Plus 增强模板", value: "plus" },
                    { label: "自定义模板", value: "custom" },
                    { label: "Uniapp 模板", value: "uniapp" }, // 新增 Uniapp 选项
                    { label: "PHP 模板", value: "php" } // 新增 PHP 选项
                ]
            },
            // 暂存待生成代码的表名（弹窗选择后使用）
            pendingTableName: ""

        };
    },
    created() {
        this.getList();
    },
    activated() {
        const time = this.$route.query.t;
        if (time != null && time != this.uniqueId) {
            this.uniqueId = time;
            this.queryParams.pageNum = Number(this.$route.query.pageNum);
            this.getList();
        }
    },
    methods: {
        /** 查询表集合 */
        getList() {
            this.loading = true;
            listTable(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
                    this.tableList = response.rows;
                    this.total = response.total;
                    this.loading = false;
                }
            );
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        showGenTemplate(){
            // 4. 打开模板选择弹窗
            this.genTemplate.open = true;
        },
        /** 生成代码操作 */
        handleGenTable(row) {
                let tableNames = []; // 初始化表名数组，避免未定义

                // 1. 判断是“单行生成”还是“批量生成”
                if (row) {
                    // 单行生成：row 存在，取当前行的 tableName（字符串）
                    tableNames = [row.tableName];
                    // 同时暂存当前行的 genType（自定义路径生成的标识），避免后续找不到
                    this.pendingGenType = row.genType;
                } else {
                    // 批量生成：row 不存在，取已选中的 this.tableNames（数组）
                    tableNames = this.tableNames;
                    // 批量生成默认用普通下载（若需支持批量自定义路径，需额外处理，此处暂用默认）
                    this.pendingGenType = "0";
                }

                // 2. 校验表名是否为空
                if (tableNames.length === 0 || !tableNames[0]) {
                    this.$modal.msgError("请选择要生成的数据表");
                    return;
                }

                // 3. 暂存表名（转为逗号分隔的字符串，适配后端接口常见格式）
                this.pendingTableName = tableNames.join(",");
                // 4. 打开模板选择弹窗
                // this.genTemplate.open = true;
            if (row.genType === "1") {
                genCode(row.tableName).then(response => {
                    this.$modal.msgSuccess("成功生成到自定义路径：" + row.genPath);
                });
            } else {
                this.$download.zip("/gen/batchGenCode?tables=" + tableNames, "generateCode");
            }
        },

        /** 同步数据库操作 */
        handleSynchDb(row) {
            const tableName = row.tableName;
            this.$modal.confirm('确认要强制同步"' + tableName + '"表结构吗？').then(function () {
                return synchDb(tableName);
            }).then(() => {
                this.$modal.msgSuccess("同步成功");
            }).catch(() => {
            });
        },
        /** 打开导入表弹窗 */
        openImportTable() {
            this.$refs.import.show();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 预览按钮 */
        handlePreview(row) {
            previewTable(row.tableId).then(response => {
                this.preview.data = response.data;
                this.preview.open = true;
                this.preview.activeName = "domain.java";
            });
        },
        /** 高亮显示 - 改造后支持 PHP */
        highlightedCode(code, key) {
            const vmName = key.substring(key.lastIndexOf("/") + 1, key.indexOf(".vm"));
            let language = vmName.substring(vmName.indexOf(".") + 1, vmName.length);

            // 新增：处理 PHP 文件的语言识别（vm 文件名如 "Model.php.vm"，提取后为 "php"）
            if (language === "php") {
                language = "php";
            }
            // 修复：Uniapp 的 Vue 文件仍用 xml 高亮（与原有 Vue 一致）
            else if (language === "vue" || key.includes("uniapp/pages/")) {
                language = "xml";
            }

            const result = hljs.highlight(language, code || "", true);
            return result.value || '&nbsp;';
        },
        /** 复制代码成功 */
        clipboardSuccess() {
            this.$modal.msgSuccess("复制成功");
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.tableId);
            this.tableNames = selection.map(item => item.tableName);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        /** 修改按钮操作 */
        handleEditTable(row) {
            const tableId = row.tableId || this.ids[0];
            const tableName = row.tableName || this.tableNames[0];
            const params = {pageNum: this.queryParams.pageNum};
            let p = {
                tableId:tableId,
                tableName:tableName,
                params:params
            }
            this.dialog.editTable.open = true
            this.dialog.editTable.params = p
        },
        handleEditClose() {
            this.dialog.editTable.open = false;
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const tableIds = row.tableId || this.ids;
            this.$modal.confirm('是否确认删除表编号为"' + tableIds + '"的数据项？').then(function () {
                return delTable(tableIds);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            });
        }
    }
};
</script>
